#!/usr/bin/python
# -*- coding: utf-8 -*-

import psycopg2
import sys
import json
import cgi
import datetime
import db_conf

con = None
try:
    qform = cgi.FieldStorage()
    experiment_id = qform.getvalue('eid')
    config = db_conf.getConfig('metabvis.conf')
    con = psycopg2.connect(host=db_conf.getDBHost(config), database=db_conf.getDBName(config), port=db_conf.getDBPort(config), user=db_conf.getUser(config), password=db_conf.getPassword(config))    
    cur = con.cursor()
    #select_experiments = 'select chromatogram_id, time_acquired, netcdf_path, operator, chrom_method from chromatogram where experiment_id = ' + experiment_id
    select_experiments = 'select c.chromatogram_id, time_acquired, netcdf_path, operator, chrom_method from chromatogram_sample_group csg, chromatogram c where csg.chromatogram_id = c.chromatogram_id and csg.experiment_id = ' + experiment_id
    cur.execute(select_experiments)          
    rows = cur.fetchall()
    print "Content-type: text/html;charset=utf-8\r\n"
    #http://chart.apis.google.com/chart?cht=bvs&chs=200x125&chd=t:10,50,60,80,40,10,50,60,80,40,10,50,60,80,40,10,50,60,80,40,10,50,60,80,40,10,50,60,80,40,10,50,60,80,40,10,50,60,80,40,10,50,60,80,40,10,50,60,80,40,10,50,60,80,40,10,50,60,80,40,10,50,60,80,40,10,50,60,80,40,10,50,60,80,40,&chco=4d89f9,c6d9fd&chbh=1,1&chds=0,160
    j = []
    pa = {}
    pa['aaData'] = []
    select_intensity = 'select RI, tic from v_chrom_intensity_sum where chromatogram_id = '
    for row in rows:
	pi = []
	for r in range(len(row)):
		pi.append(str(row[r]))
		if (r+1 == len(row)):
			chromatogram_id = str(row[0])
			select_intensity = 'select RI, tic from v_chrom_intensity_sum where chromatogram_id = ' + str(row[0])
                	cur.execute(select_intensity)
                	intensity_rows = cur.fetchall()
			ri = []
                        intensity = []
			pos = 0 
			maxpos = 0
                	for i_row in intensity_rows:
				pos = pos + 1
                        	for ii in range(len(i_row)):
                                	if (ii == 0):
                                	        ri.append(i_row[ii])
                        	        if (ii == 1):
						if (i_row[ii] > max):
							max = i_row[ii]
							maxpos = pos
                	                        intensity.append(i_row[ii])
			imin = 0
                        imax = 0
                        if (len(intensity) > 1):
                        	imin = int(min(intensity)/1000)
                        	imax = int(max(intensity)/1000)
			if (len(intensity)>500):
				begin = maxpos - 200
				if (begin < 1):
					begin = 0
				end = maxpos + 200
				if (end > len(intensity)):
					end = len(intensity)
				range_intensity = intensity[begin:end]	 
				intensities = ",".join(str(i_val/1000).split(".")[0] for i_val in range_intensity)
			else:	
	                	intensities = ",".join(str(i_val/1000).split(".")[0] for i_val in intensity)
			full_intensities = ",".join(str(i_val/1000).split(".")[0] for i_val in intensity)
			ri_values = ",".join(str(i_val/1000).split(".")[0] for i_val in ri)
			#intensity_array = full_intensities.split(",")
			#print "ri %s\n" %ri_values
			chds = "%s,%s" %(str(imin),str(imax))
			#make img a link to a js function for live plotting
			chart_url = "http://chart.apis.google.com/chart?cht=bvs&chs=200x125&chd=t:" + intensities + "&chco=4d89f9,c6d9fd&chbh=1,1&chds=" + chds 
			#10,50,60,80,40,10,50,60,80,40,10,50,60,80,40,10,50,60,80,40,10,50,60,80,40,10,50,60,80,40,10,50,60,80,40,10,50,60,80,40,10,50,60,80,40,10,50,60,80,40,10,50,60,80,40,10,50,60,80,40,10,50,60,80,40,10,50,60,80,40,10,50,60,80,40&chco=4d89f9,c6d9fd&chbh=1,1&chds=" + chds 
			pi.append("<a href=javascript:plotRIIntensity('" + chromatogram_id + "','" + full_intensities + "','" + ri_values + "')><img src='" + chart_url + "'></a>")
			#if (len(intensity)>500):
			#	intensities = ",".join(str(i_val/1000).split(".")[0] for i_val in intensity)
			#pi.append(intensities)
			#ristr =  ",".join(str(ri) for ri_val in ri)
			#pi.append(ristr)
	pa['aaData'].append(pi)
    print json.dumps(pa)
except psycopg2.DatabaseError, e:
    print 'Error %s' % e    
    sys.exit(1)    
finally:
    if con:
        con.close()
